package pl.polsl.mmm.projectcomm.objects;

import android.content.Context;

import pl.polsl.mmm.projectcomm.Constants;
import pl.polsl.mmm.projectcomm.R;
import pl.polsl.mmm.projectcomm.data.VertexArray;
import pl.polsl.mmm.projectcomm.programs.BackgroundShaderProgram;
import pl.polsl.mmm.projectcomm.util.BackgroundTextureHelper;

import static android.opengl.GLES20.GL_TRIANGLES;
import static android.opengl.GLES20.glDrawArrays;

/**
 * Obiekt i obsługa tła gry.
 * Created by Maciek on 2014-12-08.
 */
public class Background {
    private static final int REPEAT = 5; // liczba powtórzeń tła
    private static final int POSITION_COMPONENT_COUNT = 3;
    private static final int TEXTURE_COORDINATES_COMPONENT_COUNT = 2;
    private static final int STRIDE = (POSITION_COMPONENT_COUNT
            + TEXTURE_COORDINATES_COMPONENT_COUNT) * Constants.BYTES_PER_FLOAT;

    //id tekstury w api OpenGL
    private int texture;
    private final float[] vertexPositionArray = {
           -15f, -9f,  0f,     0f , 0f, //1
           -15f,  27f,  0f,     0f , 1f, //2
            15f,  27f,  0f,     1f , 1f, //3

           -15f,  -9f,  0f,     0f , 0f, //1
            15f,   27f,  0f,     1f , 1f, //3
            15f,  -9f,  0f,     1f , 0f, //4

    };
    private VertexArray vertexArray;

    public Background(Context context) {
        texture = BackgroundTextureHelper.loadTexture(context, R.drawable.background1_1);

        float[] vertexMultipliedPositionArray = new float[REPEAT * 6 * 5];

        // Powielanie tła REPEAT razy (w prawo)
        for (int i = 0; i < REPEAT; i++) {
            for (int j = 0; j < 30; j++) {
                vertexMultipliedPositionArray[i * 30 + j] = vertexPositionArray[j];
                if (j % 5 == 0) {
                    vertexMultipliedPositionArray[i * 30 + j] += 30*i;
                }
            }
        }

//        vertexArray = new VertexArray(vertexPositionArray);
        vertexArray = new VertexArray(vertexMultipliedPositionArray);
    }

    public void bindData(BackgroundShaderProgram textureProgram) {
        textureProgram.setTexture(texture);
        vertexArray.setVertexAttribPointer(
                0,
                textureProgram.getPositionAttributeLocation(),
                POSITION_COMPONENT_COUNT,
                STRIDE);
        vertexArray.setVertexAttribPointer(
                POSITION_COMPONENT_COUNT,
                textureProgram.getTextureCoordinatesAttributeLocation(),
                TEXTURE_COORDINATES_COMPONENT_COUNT,
                STRIDE);
    }

    public void draw() {
        glDrawArrays(GL_TRIANGLES,0,6*REPEAT);
    }
}
